const v_shader_source = `
  attribute vec4 a_Position;
  attribute vec2 a_TexCoord;
  varying vec2 v_TexCoord;
  void main(){
    gl_Position = a_Position;
    v_TexCoord = a_TexCoord;
  }
`;

const f_shader_source = `
  precision mediump float;
  varying vec2 v_TexCoord;
  uniform sampler2D u_Sampler;
  void main(){
   gl_FragColor =  texture2D(u_Sampler,v_TexCoord);
  }
`;

window.addEventListener('load', e => {
  const canvas = document.getElementById('canvas');
  const gl = getWebGLContext(canvas);
  initShaders(gl, v_shader_source, f_shader_source);

  let verticesTexCoords = new Float32Array([-0.5, 0.5, 0.0, 1.0, -0.5, -0.5, 0.0, 0.0, 0.5, 0.5, 1.0, 1.0, 0.5, -0.5, 1.0, 1.0]);

  let vertexTexCoordBuffer = gl.createBuffer();

  gl.bindBuffer(gl.ARRAY_BUFFER, vertexTexCoordBuffer);
  gl.bufferData(gl.ARRAY_BUFFER, verticesTexCoords, gl.STATIC_DRAW);

  const FSIZE = verticesTexCoords.BYTES_PER_ELEMENT;

  let a_Position = gl.getAttribLocation(gl.program, 'a_Position');
  gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, FSIZE * 4, 0);
  gl.enableVertexAttribArray(a_Position);

  let a_TexCoord = gl.getAttribLocation(gl.program, 'a_TexCoord');
  gl.vertexAttribPointer(a_TexCoord, 2, gl.FLOAT, false, 4 * FSIZE, 2 * FSIZE);
  gl.enableVertexAttribArray(a_TexCoord);
  initTextures(gl);
});

const initTextures = gl => {
  const image = new Image();
  image.src = '/samples/image/cat.jpg';
  image.onload = () => {
    loadText(gl, image);
  };
};
const loadText = (gl, image) => {
  let texture = gl.createTexture();
  gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);

  gl.activeTexture(gl.TEXTURE0);
  gl.bindTexture(gl.TEXTURE_2D, texture);

  // gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  // gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
  // gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);

  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);

  gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);

  let u_Sampler = gl.getUniformLocation(gl.program, 'u_Sampler');
  gl.uniform1i(u_Sampler, 0);

  gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
};